<template>
    <div class="container">
        <!-- 搜索栏 -->
        <div class="search-container">
            <template v-if="!isDetail">
                <input type="text" placeholder="跟单编号" v-model="searchParams.Batch_number" class="search-input" />
                <input type="text" placeholder="单据编号" v-model="searchParams.Production_Material_Id"
                    class="search-input" />
                <input type="text" placeholder="物料编码" v-model="searchParams.Material_code" class="search-input" />
                <input type="text" placeholder="物料名称" v-model="searchParams.Name" class="search-input" />
            </template>
            <template v-else>
                <input type="text" placeholder="单据编码" v-model="searchParams.Production_Material_Id"
                    class="search-input" />
                <select v-model="searchParams.Status" class="search-select">
                    <option value="">单据状态</option>
                    <option value="审核">审核</option>
                </select>
                <!-- 新增业务状态下拉菜单 -->
                <select v-model="searchParams.Business_status" class="search-select">
                    <option value="">业务状态</option>
                    <option value="系统关闭">系统关闭</option>
                    <option value="正常运行">正常运行</option>
                </select>
            </template>
            <div class="date-range">
                <input type="date" v-model="searchParams.start_date" />
                <span>至</span>
                <input type="date" v-model="searchParams.end_date" />
            </div>
            <button @click="handleSearch" class="search-button">搜索</button>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button class="btn btn-primary" @click="toggleDetail">
                {{ isDetail ? '单据' : '明细' }}
            </button>
            <button class="btn btn-success" @click="handleCreate">
                {{ isDetail ? '新建' : '新建' }}
            </button>
            <button class="btn btn-warning" @click="handleExport">
                导出{{ isDetail ? '单据' : '生产' }}数据
            </button>
            <template v-if="isDetail">
                <button class="btn btn-danger" @click="handleDelete">删除</button>
                <button class="btn btn-info" @click="handleApprove">审核</button>
                <button class="btn btn-secondary" @click="handleReject">反审核</button>
            </template>
        </div>

        <!-- 动态表格 -->
        <template v-if="!isDetail">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>跟单编号</th>
                        <th>单据编码</th>
                        <th>单据状态</th>
                        <th>生产订单</th>
                        <th>物料名称</th>
                        <th>物料编号</th>
                        <th>仓库</th>
                        <th>领用数量</th>
                        <th>出库数量</th>
                        <th>单据日期</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in tableData" :key="item.SCDD_id">
                        <td>{{ index + 1 }}</td>
                        <td>{{ item.production_Material_BatchNumber }}</td>
                        <td>{{ item.production_Material_Id }}</td>
                        <td>{{ item.production_Material_Status }}</td>
                        <td>{{ item.production_Material_ProductionOrderId }}</td>
                        <td>{{ item.productionWUName }}</td>
                        <td>{{ item.productionWUId }}</td>
                        <td>{{ item.production_Material_Warehouse }}</td>
                        <td>{{ item.used_qty }}</td>
                        <td>{{ item.out_qty }}</td>
                        <td>{{ formatDate(item.production_Material_DocumentDate) }}</td>
                    </tr>
                </tbody>
            </table>
        </template>

        <template v-else>
            <table class="data-table">
                <thead>
                    <tr>
                        <th><input type="checkbox" v-model="isAllChecked" @change="handleAllCheck"></th>
                        <th>单据编码</th>
                        <th>单据日期</th>
                        <th>单据状态</th>
                        <th>业务类型</th>
                        <th>业务状态</th>
                        <th>审核日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in detailTableData" :key="item.id">
                        <td><input type="checkbox" v-model="item.isChecked" @change="handleSingleCheck(item)"></td>
                        <td>{{ item.production_Material_BatchNumber }}</td>
                        <td>{{ formatDate(item.production_Material_DocumentDate) }}</td>
                        <td>{{ item.production_Material_Status }}</td>
                        <td>{{ item.production_Material_BusinessType }}</td>
                        <td>{{ item.producMaterialSate }}</td>
                        <td>{{ formatDate(item.audit_date) }}</td>
                        <td>
                            <button class="link-btn" @click="Show(item.production_Material_Id)">查看</button>
                            <button class="link-btn">编辑</button>
                            <button class="link-btn danger">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </template>

        <!-- 分页组件 -->
        <div class="pagination">
            <span>共{{ searchParams.total_count }}条</span>
            <select v-model="searchParams.PageSize" @change="handlePageSizeChange">
                <option value="10">10条/页</option>
                <option value="20">20条/页</option>
                <option value="50">50条/页</option>
                <option value="100">100条/页</option>
            </select>
            <div class="page-control">
                <button :disabled="searchParams.current_page <= 1" @click="prevPage">‹</button>
                <span>第 {{ searchParams.current_page }} 页 / 共 {{ searchParams.current_page }} 页</span>
                <button :disabled="searchParams.current_page >= totalPages" @click="nextPage">›</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, watchEffect } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElTable } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { KongaUrl } from '@/axios/axiosHelp'
import * as XLSX from 'xlsx'; // 使用命名空间导入
import { saveAs } from 'file-saver';

const router = useRouter();
const route = useRoute();




// 响应式状态
const isDetail = ref(false)
const tableData = ref([])
const detailTableData = ref([])
const isAllChecked = ref(false)

const searchParams = ref({
    start_date: '',
    end_date: '',

    Batch_number: '',
    Material_code: '',
    Name: '',
    Production_Material_Id: '',
    Status: '',
    Business_status: '',

    totalPages: 0,
    current_page: 1,
    PageSize: 10,
    total_count: 0,
})


// 模拟数据（实际需替换为API请求）
watchEffect(() => {
    if (!isDetail.value) {



    } else {
        KongaUrl.get(`/shengchandu/api/ProductionMaterialRequest/ProductionMaterialShow`, {
            params: {
                PageIndex: searchParams.value.current_page, // 修正拼写并添加 .value
                PageSize: searchParams.value.PageSize,

                Batch_number: searchParams.value.Batch_number,
                Production_Material_Id: searchParams.value.Production_Material_Id,
                Material_code: searchParams.value.Material_code,
                Name: searchParams.value.Name,
                Status: searchParams.value.Status,
                Business_status: searchParams.value.Business_status,

                ProductionStartDate: searchParams.value.start_date,
                ProductionEndDate: searchParams.value.end_date,
            }
        }).then(res => {
            detailTableData.value = res.data.data.list;
            searchParams.value.total_count = res.data.data.totalCount;
            searchParams.value.total_page = res.data.data.totalPage;
        }).catch(error => {
            ElMessage.error('数据加载失败');
            console.error(error);
        });
    }
})
const Fomw = () => {
    KongaUrl.get(`/shengchandu/api/ProductionMaterialRequest/ProductionMaterialShow`, {
        params: {
            PageIndex: searchParams.value.current_page, // 修正拼写并添加 .value
            PageSize: searchParams.value.PageSize,

            Batch_number: searchParams.value.Batch_number,
            Production_Material_Id: searchParams.value.Production_Material_Id,
            Material_code: searchParams.value.Material_code,
            Name: searchParams.value.Name,
            Status: searchParams.value.Status,
            Business_status: searchParams.value.Business_status,

            ProductionStartDate: searchParams.value.start_date,
            ProductionEndDate: searchParams.value.end_date,
        }
    }).then(res => {
        console.log(res)
        tableData.value = res.data.data.list;
        searchParams.value.total_count = res.data.data.totalCount;
        searchParams.value.total_page = res.data.data.totalPage;
    }).catch(error => {
        ElMessage.error('数据加载失败');
        console.error(error);
    });
}
// 切换视图
const toggleDetail = () => {
    isDetail.value = !isDetail.value
    searchParams.value.current_page = 1
}

// 搜索
const handleSearch = () => {
    Fomw()
    searchParams.value.current_page = 1
}

// 分页大小变化
const handlePageSizeChange = () => {
    searchParams.value.current_page = 1
}

// 翻页
const prevPage = () => {
    if (searchParams.value.current_page > 1) {
        searchParams.value.current_page--
    }
}

const nextPage = () => {
    if (searchParams.value.current_page < totalPages.value) {
        searchParams.value.current_page++
    }
}

// 全选和单选逻辑
const handleAllCheck = () => {
    detailTableData.value.forEach(item => {
        item.isChecked = isAllChecked.value
    })
}

const handleSingleCheck = (item) => {
    const allChecked = detailTableData.value.every(item => item.isChecked)
    isAllChecked.value = allChecked
}

// 日期格式化
const formatDate = (date) => dayjs(date).format('YYYY - MM - DD')

// 删除和审核逻辑
const handleDelete = () => {
    detailTableData.value = detailTableData.value.filter(item => !item.isChecked)
    searchParams.value.total_count = detailTableData.value.length
}

const handleApprove = () => {
    detailTableData.value.forEach(item => {
        if (item.isChecked) {
            item.status = '审核'
        }
    })
}

const handleReject = () => {
    detailTableData.value.forEach(item => {
        if (item.isChecked) {
            item.status = '反审核'
        }
    })
}
//新增
const handleCreate = () => {
    router.push("/ProductionpickingAdd")
}
// 修改导出方法
const handleExport = () => {
    const exportData = isDetail.value ? detailTableData.value : tableData.value;

    if (exportData.length === 0) {
        ElMessage.warning('当前没有数据可导出');
        return;
    }

    const columnConfig = {
        list: [
            { key: 'production_Material_BatchNumber', title: '跟单编号' },
            { key: 'production_Material_Id', title: '单据编码' },
            { key: 'production_Material_Status', title: '单据状态' },
            { key: 'production_Material_ProductionOrderId', title: '生产订单' },
            { key: 'productionWUName', title: '物料名称' },
            { key: 'productionWUId', title: '物料编号' },
            { key: 'production_Material_Warehouse', title: '仓库' },
            { key: 'used_qty', title: '领用数量' },
            { key: 'out_qty', title: '出库数量' },
            { key: 'production_Material_DocumentDate', title: '单据日期' }
        ],
        detail: [
            { key: 'production_Material_BatchNumber', title: '单据编码' },
            { key: 'production_Material_DocumentDate', title: '单据日期' },
            { key: 'production_Material_Status', title: '单据状态' },
            { key: 'production_Material_BusinessType', title: '业务类型' },
            { key: 'producMaterialSate', title: '业务状态' },
            { key: 'audit_date', title: '审核日期' }
        ]
    };

    const processedData = exportData.map((item, index) => {
        const row = {
            ...(isDetail.value ? {} : { 序号: index + 1 }),
        };

        columnConfig[isDetail.value ? 'detail' : 'list'].forEach(col => {
            let value = item[col.key];
            if (col.key.endsWith('Date')) {
                value = formatDate(value);
            }
            row[col.title] = value;
        });

        return row;
    });

    const worksheet = XLSX.utils.json_to_sheet(processedData); // 注意这里用 XLSX.utils
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '数据');
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

    const fileName = isDetail.value ? '单据数据导出.xlsx' : '生产数据导出.xlsx';
    saveAs(blob, fileName);
};

const Show = (id) => {
    router.push(`/ProductionpickingUpdate?production_Material_Id=${id}`)
}

onMounted(() => {
    watchEffect()
    Fomw()
})
</script>

<style scoped>
.container {
    padding: 20px;
    background: #f5f7fa;
}

.search-container {
    display: flex;
    flex-wrap: nowrap;
    gap: 12px;
    margin-bottom: 20px;
}

.search-input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.search-input,
.search-select {
    flex: 1;
    min-width: 200px;
    /* 或根据需要调整 */
}

.date-range {
    display: flex;
    gap: 10px;
    align-items: center;
}

.search-button {
    padding: 8px 16px;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.action-buttons {
    margin-bottom: 20px;
}

.btn {
    padding: 8px 15px;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;
}

.btn-primary {
    background: #409eff;
    color: white;
    border: 1px solid #409eff;
}

.btn-success {
    background: #67c23a;
    color: white;
    border: 1px solid #67c23a;
}

.btn-warning {
    background: #e6a23c;
    color: white;
    border: 1px solid #e6a23c;
}

.btn-danger {
    background: #f56c6c;
    color: white;
    border: 1px solid #f56c6c;
}

.btn-info {
    background: #66b1ff;
    color: white;
    border: 1px solid #66b1ff;
}

.btn-secondary {
    background: #909399;
    color: white;
    border: 1px solid #909399;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    margin-bottom: 20px;
}

.data-table th,
.data-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #e8e8e8;
    text-align: left;
}

.data-table th {
    background: #fafafa;
    font-weight: 500;
}

.pagination {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 15px;
    background: white;
    border-radius: 4px;
}

.link-btn {
    color: #409eff;
    cursor: pointer;
    background: none;
    border: none;
    padding: 0 5px;
}

.link-btn.danger {
    color: #f56c6c;
}

.text-green {
    color: #67c23a;
}

input[type="checkbox"] {
    transform: scale(1.2);
    margin-right: 5px;
    vertical-align: middle;
}
</style>